package com.kgc.personconsumer.controller;

import com.kgc.basic.util.ResponseMsg;
import com.kgc.personcommon.pojo.User;
import com.kgc.personconsumer.feign.UserFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserFeign userFeign;

    @RequestMapping("getPage")
    @ResponseBody
    public ResponseMsg getPage(@RequestParam String pageNow,
                               @RequestParam String pageSize,
                               @RequestParam(required = false) String account,
                               @RequestParam(required = false) String name) {
        logger.info("UserController getPage pageNow={} pageSize={} account={} name={}",
                pageNow, pageSize, account, name);
        Map<String, Object> m = new HashMap<>();
        m.put("pageNow", Integer.parseInt(pageNow));
        m.put("pageSize", Integer.parseInt(pageSize));
        m.put("account", account);
        m.put("name", name);

        ResponseMsg response = userFeign.getUserPage(m);
        logger.debug("userFeign.getUserPage params={} → response={}", m, response);
        return response;
    }

    @PostMapping("add")
    @ResponseBody
    public ResponseMsg add(@RequestBody User user) {
        logger.info("UserController add user={}", user);
        ResponseMsg response = userFeign.addUser(user);
        logger.debug("userFeign.addUser user={} → response={}", user, response);
        return response;
    }

    @PostMapping("update")
    @ResponseBody
    public ResponseMsg update(@RequestBody User user) {
        logger.info("UserController update user={}", user);
        ResponseMsg response = userFeign.updateUser(user);
        logger.debug("userFeign.updateUser user={} → response={}", user, response);
        return response;
    }

    @PostMapping("del")
    @ResponseBody
    public ResponseMsg del(@RequestParam Integer id) {
        logger.info("UserController del id={}", id);
        ResponseMsg response = userFeign.delUser(id);
        logger.debug("userFeign.delUser id={} → response={}", id, response);
        return response;
    }

    @RequestMapping("getById")
    @ResponseBody
    public ResponseMsg getById(@RequestParam Integer id) {
        logger.info("UserController getById id={}", id);
        ResponseMsg response = userFeign.getUserById(id);
        logger.debug("userFeign.getUserById id={} → response={}", id, response);
        return response;
    }

//    @PreAuthorize("hasAuthority('/per/user/getAll')")
    @RequestMapping("getAll")
    @ResponseBody
    public ResponseMsg getAll() {
        logger.info("UserController getAll");
        ResponseMsg response = userFeign.getAllUser(new HashMap<>());
        logger.debug("userFeign.getAllUser → response={}", response);
        return response;
    }

    @RequestMapping("login")
    @ResponseBody
    public ResponseMsg login(String account, String password, String checkCode) {
        logger.info("consumer UserController login account:{},password:{},checkCode:{}", account, password, checkCode);
        ResponseMsg msg = userFeign.login(account, password, checkCode);
        logger.debug("consumer UserController login msg:{}", msg);
        return msg;
    }

    @RequestMapping("getCaptcha")
    @ResponseBody
    public void getCaptcha(HttpServletResponse response) throws IOException {
        String base64Image = userFeign.getCaptcha();
        if (base64Image != null) {
            response.setContentType("image/jpeg");
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            response.getOutputStream().write(imageBytes);
        }
    }

    @RequestMapping("logout")
    @ResponseBody
    public ResponseMsg logout(@RequestBody Map<String, String> request, HttpSession session) {
        logger.info("consumer UserController is start...");
        String sessionId = request.get("sessionId");
        if (sessionId == null || sessionId.isEmpty()) {
            ResponseMsg msg = new ResponseMsg();
            msg.setCode("400");
            msg.setMsg("缺少sessionId参数");
            return msg;
        }
        Map<String, String> feignRequest = new HashMap<>();
        feignRequest.put("sessionId", sessionId);
        ResponseMsg msg = userFeign.logout(feignRequest);
        session.invalidate();
        logger.debug("consumer UserController msg:{}", msg);
        return msg;
    }

    @RequestMapping("getPremByUid")
    @ResponseBody
    public ResponseMsg getPremByUid(@RequestParam String account) {
        logger.info("UserController getPremByUid uid={}", account);
        ResponseMsg responseMsg = userFeign.getTreePermissionsByUserId(account);
        logger.debug("userFeign getTreePermissionsByUserId uid={}", account +",responseMsg:"+responseMsg);
        return responseMsg;
    }

    @RequestMapping("refresh")
    @ResponseBody
    public ResponseMsg refresh(@RequestBody Map<String, String> map) {
        logger.info("UserController refresh map={}", map);
        ResponseMsg responseMsg = userFeign.refresh(map);
        logger.debug("userFeign.refresh map={}", map);
        return responseMsg;
    }
    @RequestMapping("selectUserByDept")
    @ResponseBody
    public ResponseMsg selectUserByDept(@RequestBody Map<String, Object> map){
        logger.info("consumer UserController selectUserByDept");
        ResponseMsg responseMsg = userFeign.selectUserByMap(map);
        logger.info("consumer UserController selectUserByMap map{} ,response{}", map,responseMsg);
        return responseMsg;
    }
}
